package com.qsmx.qingqiuticket.app.delegate;

import static androidx.core.content.ContextCompat.registerReceiver;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.al.printerlib.device.CallbackListener;
import com.al.printerlib.device.Printer;
import com.al.printerlib.device.PrinterStatus;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.loader.AtmosLoader;
import com.qsmx.core.util.log.AtmosLogger;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.delegate.back.BackSettingDelegate;
import com.qsmx.qingqiuticket.app.delegate.back.MachineSettingDelegate;
import com.qsmx.qingqiuticket.app.delegate.back.PasswordDelegate;
import com.qsmx.qingqiuticket.app.delegate.back.camera.CameraTestDelegate;
import com.qsmx.qingqiuticket.app.entity.AdvEntity;
import com.qsmx.qingqiuticket.app.entity.BaseEntity;
import com.qsmx.qingqiuticket.app.entity.InitMachineEntity;
import com.qsmx.qingqiuticket.app.event.CheckNextPrintEvent;
import com.qsmx.qingqiuticket.app.event.CheckPrintEvent;
import com.qsmx.qingqiuticket.app.event.CheckTicketWaringEvent;
import com.qsmx.qingqiuticket.app.event.HomeRefreshEvent;
import com.qsmx.qingqiuticket.app.event.PrintFinishEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.service.HeartBeatService;
import com.qsmx.qingqiuticket.app.util.ApkManager;
import com.qsmx.qingqiuticket.app.util.CameraManager;
import com.qsmx.qingqiuticket.app.util.FileUtil;
import com.qsmx.qingqiuticket.app.util.OpenUDID;
import com.qsmx.qingqiuticket.app.util.SaveHelper;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class IndexDelegate extends AtmosDelegate {

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    AppCompatTextView tvPrint1Status;
    AppCompatTextView tvPrint2Status;
    AppCompatTextView tvPrint3Status;

    AppCompatTextView tvGoSet;
    private List<UsbDevice> mUsbList;
    UsbManager manager;
    private Printer mDevice;

    private Dialog printStatusDialog;

    private String printStatus;

    @Override
    public Object setLayout() {
        return R.layout.delegate_index;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        initData();
        IndexDelegatePermissionsDispatcher.startCheckFileWithCheck(IndexDelegate.this);
//        if (AtmosPreference.getCustomIntPre(FusionPre.VERSION_LOG) != 0) {
//            if (AtmosPreference.getCustomIntPre(FusionPre.VERSION_LOG) < ApkManager.getVersionCode(getContext())) {
//                IndexDelegatePermissionsDispatcher.startCheckFileWithCheck(IndexDelegate.this);
//            }
//        } else {
//            AtmosPreference.addCustomIntPre(FusionPre.VERSION_LOG, ApkManager.getVersionCode(getContext()));
//        }
    }

    private void initData() {
        if (StringUtil.isNotEmpty(AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM))) {
            initMachineData();
            getUsbDeviceList();
        } else {
            getSupportDelegate().start(MachineSettingDelegate.create(true));
        }
    }

    private void checkPrintStatus() {
        if (printStatusDialog != null && printStatusDialog.isShowing()) {
            return;
        }
        printStatusDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        printStatusDialog.setCancelable(false);
        printStatusDialog.show();
        Window window = printStatusDialog.getWindow();
        window.setContentView(R.layout.dialog_check_print_status);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        tvPrint1Status = printStatusDialog.findViewById(R.id.tv_print_1_status);
        tvPrint2Status = printStatusDialog.findViewById(R.id.tv_print_2_status);
        tvPrint3Status = printStatusDialog.findViewById(R.id.tv_print_3_status);
        tvGoSet = printStatusDialog.findViewById(R.id.tv_go_set);
        doPrint("1");

        tvGoSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                printStatusDialog.dismiss();
                getSupportDelegate().start(new PasswordDelegate());
            }
        });
    }

    private void checkTicketWaring() {
        if (!printStatusDialog.isShowing()) {
            if (StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM), 0) <= StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_WARING_TICKET_NUM), 0)) {
                DialogUtil.showNoTicketDialog(IndexDelegate.this, requireContext(), "打印机-1票数已低于预警值，请及时补充！", "确定", new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        DialogUtil.dismissTicketDialog();
                        getSupportDelegate().start(new PasswordDelegate());
                    }
                });
            } else if (StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM), 0) <= StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_WARING_TICKET_NUM), 0)) {
                DialogUtil.showNoTicketDialog(IndexDelegate.this, requireContext(), "打印机-2票数已低于预警值，请及时补充！", "确定", new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        DialogUtil.dismissTicketDialog();
                        getSupportDelegate().start(new PasswordDelegate());
                    }
                });
            } else if (StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM), 0) <= StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_WARING_TICKET_NUM), 0)) {
                DialogUtil.showNoTicketDialog(IndexDelegate.this, requireContext(), "打印机-3票数已低于预警值，请及时补充！", "确定", new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        DialogUtil.dismissTicketDialog();
                        getSupportDelegate().start(new PasswordDelegate());
                    }
                });
            }
        }
    }


    /**
     * 获取USB设备列表
     */
    @SuppressLint("NotifyDataSetChanged")
    public void getUsbDeviceList() {
        mUsbList = new ArrayList<>();
        manager = (UsbManager) getProxyActivity().getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devices = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = devices.values().iterator();
        int count = devices.size();
        AtmosLogger.d("count " + count);
        if (count > 0) {
            while (deviceIterator.hasNext()) {
                UsbDevice device = deviceIterator.next();
                PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0,
                        new Intent(ACTION_USB_PERMISSION),
                        Build.VERSION.SDK_INT >= 34 ? PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_MUTABLE);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);//USB插入
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);//USB拔出
                registerReceiver(requireContext(), mUsbReceiver, filter, ContextCompat.RECEIVER_EXPORTED);

                if (manager.hasPermission(device)) {
                    if (checkUsbDevicePidVid(device)) {
                        mUsbList.add(device);
                    }
                } else {
                    //请求USB设备权限
                    manager.requestPermission(device, mPermissionIntent);
                }
            }
        } else {
            String noDevices = getResources().getText(R.string.none_usb_device).toString();
            AtmosLogger.d("noDevices " + noDevices);
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public String checkDeviceName(String PrintNo) {
        String deviceName = "";
        if (mUsbList != null && !mUsbList.isEmpty()) {
            for (UsbDevice device : mUsbList) {
                if (Objects.equals(device.getSerialNumber(), PrintNo)) {
                    deviceName = device.getDeviceName();
                }
            }
        }
        return deviceName;
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (getSupportDelegate().isSupportVisible()) {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if (device != null) {
                                if (checkUsbDevicePidVid(device)) {
                                    mUsbList.add(device);
                                }
//                                checkPrintStatus();
                                Toast.makeText(context, "设备授权成功", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(context, "设备拒绝授权", Toast.LENGTH_LONG).show();
                        }
                    }
                } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    Toast.makeText(context, "USB已插入", Toast.LENGTH_LONG).show();
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    Toast.makeText(context, "USB已拔出", Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    /**
     * 检查USB设备的PID与VID
     *
     * @param dev
     * @return
     */
    boolean checkUsbDevicePidVid(UsbDevice dev) {
        int pid = dev.getProductId();
        int vid = dev.getVendorId();
        return (vid == 0x5a5a && pid == 0x8009);
    }

    private void doPrint(String printType) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (printType.equals("1")) {
                    String deviceName = checkDeviceName(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE));
                    connectUsbDevice(deviceName, "print", "1");
                } else if (printType.equals("2")) {
                    String deviceName = checkDeviceName(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO));
                    connectUsbDevice(deviceName, "print", "2");
                } else if (printType.equals("3")) {
                    String deviceName = checkDeviceName(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE));
                    connectUsbDevice(deviceName, "print", "3");
                }
            }
        }).start();
    }

    private void connectUsbDevice(String serialNumber, String type, String printNo) {
        mDevice = new Printer(requireContext(), serialNumber, new CallbackListener() {
            @Override
            public void onConnecting() {
                AtmosLogger.d("连接中...");
                if (printNo.equals("1")) {
                    tvPrint1Status.setText("连接中...");
                } else if (printNo.equals("2")) {
                    tvPrint2Status.setText("连接中...");
                } else if (printNo.equals("3")) {
                    tvPrint3Status.setText("连接中...");
                }
            }

            @Override
            public void onSuccess(String name) {
                if (type.equals("print")) {
                    if (mDevice != null) {
                        PrinterStatus test = getPrinterStatus(mDevice, 500);
                        if (test != null) {
                            if (printNo.equals("1")) {
                                tvPrint1Status.setText(setPrintStatus(tvPrint1Status, test));
                            } else if (printNo.equals("2")) {
                                tvPrint2Status.setText(setPrintStatus(tvPrint2Status, test));
                            } else if (printNo.equals("3")) {
                                tvPrint3Status.setText(setPrintStatus(tvPrint3Status, test));
                            }

                            if (tvPrint1Status.getText().toString().equals("正常") && tvPrint2Status.getText().toString().equals("正常") && tvPrint3Status.getText().toString().equals("正常")) {
                                printStatusDialog.dismiss();
                                checkTicketWaring();
                            } else {
                                if (tvPrint1Status.getText().toString().equals("重新获取") || tvPrint2Status.getText().toString().equals("重新获取") || tvPrint3Status.getText().toString().equals("重新获取")) {
                                    connectUsbDevice(serialNumber, "print", printNo);
                                }
                            }

                            Bundle bundle = new Bundle();
                            bundle.putInt("printNo", StringUtil.IntegerValueOf(printNo, 0));
                            EventBus.getDefault().post(new CheckNextPrintEvent(bundle));
                        } else {
                            connectUsbDevice(serialNumber, "print", printNo);
                        }
                    } else {
                        DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                    }
                }
            }

            @Override
            public void onReceive(byte[] data) {

            }

            @Override
            public void onFailure() {
                AtmosLogger.d("连接失败");
                if (printNo.equals("1")) {
                    tvPrint1Status.setText("连接失败");
                } else if (printNo.equals("2")) {
                    tvPrint2Status.setText("连接失败");
                } else if (printNo.equals("3")) {
                    tvPrint3Status.setText("连接失败");
                }

                Bundle bundle = new Bundle();
                bundle.putInt("printNo", StringUtil.IntegerValueOf(printNo, 0));
                EventBus.getDefault().post(new CheckNextPrintEvent(bundle));
            }

            @Override
            public void onDisconnect() {
                AtmosLogger.d("断开连接");

            }
        });
        mDevice.OpenPort();
    }

    private static PrinterStatus getPrinterStatus(Printer device, int timeoutms) {
        PrinterStatus pst = new PrinterStatus();
        int result = device.GetStatus(pst, timeoutms);
        if (result != 0) {
            return null;
        }
        return pst;
    }

    private String setPrintStatus(AppCompatTextView tv, PrinterStatus printStatus) {
        tv.setTextColor(requireContext().getColor(com.qsmx.core.R.color.font_red_color));
        if (printStatus.bPrinterStatePaperEnd) {
            return "纸张不足";
        } else if (printStatus.bPrinterStatePaperNearEnd) {
            return "纸将尽";
        } else if (printStatus.bPrinterStatePlateOpen) {
            return "开盖错误";
        } else if (printStatus.bPrinterStateCutterError) {
            return "切刀错误";
        } else if (printStatus.bPrinterStateHighTmError) {
            return "热敏感问多过高";
        } else if (printStatus.bPrinterStatePaperJam) {
            return "堵纸错误";
        } else if (printStatus.bPrinterStateHighVoltage) {
            return "高压错误";
        } else if (printStatus.bPrinterStateLowVoltage) {
            return "低压错误";
        } else if (printStatus.bPrinterStateBlackMarkError) {
            return "黑标错误";
        } else if (printStatus.bPrinterStatePrinting) {
            return "正在打印";
        } else if (printStatus.bPrinterStateTestPrinting) {
            return "正在打印自检页";
        } else if (printStatus.bPrinterStateRedundantError) {
            return "冗纸错误";
        } else if (printStatus.bPrinterStateRamError) {
            return "RAM错误";
        } else {
            if (printStatus.btPlateOpenAD != 0 && printStatus.btPaperEndAD != 0) {
                tv.setTextColor(requireContext().getColor(R.color.black));
                return "正常";
            } else {
                return "重新获取";
            }
        }
    }

    private void initMachineData() {
        try {
            AtmosLoader.showLoading(getContext());
            JSONObject params = new JSONObject();
            params.put("storeShortName", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM));
            params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
            if (StringUtil.isEmpty(OpenUDID.getOpenUDID())) {
                params.put("mac", "1");
            } else {
                params.put("mac", OpenUDID.getOpenUDID());
            }
            params.put("version", ApkManager.getVersionName(getContext()));

            HttpHelper.RestClientPostRaw(params, HttpUrl.INIT_DATE,
                    new ISuccess() {
                        @Override
                        public void onSuccess(int code, String response) {
                            AtmosLoader.stopLoading();
                            try {
                                Type type = new TypeToken<InitMachineEntity>() {
                                }.getType();
                                Gson gson = new Gson();
                                InitMachineEntity mData = gson.fromJson(response, type);
                                if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                    AtmosPreference.addCustomStringPre(FusionPre.STORE_NAME, mData.getBody().getStoreName());
                                    AtmosPreference.addCustomStringPre(FusionPre.MINI_CODE, mData.getBody().getQrCode());
                                    initAdv();
                                    Intent serviceIntent = new Intent(getContext(), HeartBeatService.class);
                                    getProxyActivity().startService(serviceIntent);
                                } else {
                                    getSupportDelegate().start(MachineSettingDelegate.create(true));
                                }
                            } catch (Exception e) {
                                DialogUtil.showCardErrorDialog(IndexDelegate.this, getContext(), getString(R.string.service_error), "重试", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        DialogUtil.dismissErrorDialog();
                                        initMachineData();
                                    }
                                });
                            }
                        }
                    }, new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            AtmosLoader.stopLoading();
                            DialogUtil.showCardErrorDialog(IndexDelegate.this, getContext(), msg, "重试", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DialogUtil.dismissErrorDialog();
                                    initMachineData();
                                }
                            });
                        }
                    }, new IFailure() {
                        @Override
                        public void onFailure() {
                            AtmosLoader.stopLoading();
                            DialogUtil.showCardErrorDialog(IndexDelegate.this, getContext(), getString(R.string.un_know_net_error), "重试", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DialogUtil.dismissErrorDialog();
                                    initMachineData();
                                }
                            });
                        }
                    });
        } catch (Exception e) {
            showLongToast("初始化异常，请重启app");
        }
    }

    private void initAdv() {
        JSONObject params = new JSONObject();
        params.put("storeShortName", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM));
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        HttpHelper.RestClientPostRaw(params, HttpUrl.GET_ADV,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        try {
                            Type type = new TypeToken<AdvEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            AdvEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                FusionData.mAdvData = mData;
                                getSupportDelegate().loadRootFragment(R.id.delegate_container, new HomeDelegate());

                            }
                        } catch (Exception e) {
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startCheckFile() {
        initLogPath();
        FileUtil.deleteFolderFile(SaveHelper.getSaveVideoPath());
        CameraManager.initCamera(requireContext());
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileRational(PermissionRequest request) {
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileDenied() {
        DialogUtil.showHasNoPermissionDialog(requireContext(), new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getProxyActivity().finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNeverFile() {
        DialogUtil.showHasNoPermissionDialog(requireContext(), new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getProxyActivity().finish();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        IndexDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    private void initLogPath() {

        final File filepath = new File(FusionCode.SAVE_PATH + "log");
        if (!filepath.exists()) {
            filepath.mkdirs();
        }

        File logFile = new File(FusionCode.LOG_PATH + "version_log.txt");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
                FileUtil.writeData(StringUtil.getDateToStringTodayHasHour(System.currentTimeMillis()) + "|||Version=============>" + ApkManager.getVersionName(getContext()));
                AtmosPreference.addCustomIntPre(FusionPre.VERSION_LOG, ApkManager.getVersionCode(getContext()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCheckPrintEvent(CheckPrintEvent event) {
        if (event != null && event.getData() != null) {
            checkPrintStatus();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCheckWaringEvent(CheckTicketWaringEvent event) {
        if (event != null && event.getData() != null) {
            checkTicketWaring();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCheckNextPrintEvent(CheckNextPrintEvent event) {
        if (isVisible()) {
            if (event != null && event.getData() != null) {
                if (event.getData().getInt("printNo") < 3) {
                    doPrint(String.valueOf(event.getData().getInt("printNo") + 1));
                } else {
                    if (!tvPrint1Status.getText().toString().equals("正常") || !tvPrint2Status.getText().toString().equals("正常") || !tvPrint3Status.getText().toString().equals("正常")) {
                        tvGoSet.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(HomeRefreshEvent event) {
        if (event != null && event.getData() != null) {
            initData();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
    }
}
